import { ref, watch, onUnmounted } from 'vue'
import { ElNotification } from 'element-plus'

export function useWebSocket(url) {
    const socket = ref(null)
    const messages = ref([]) // 收到的消息队列
    const messageQueue = ref([]) // 待发送消息队列（网络中断时缓冲）
    const isConnected = ref(false)
    const reconnectAttempts = 5 // 最大重试次数
    const reconnectInterval = 3000 // 重试间隔(ms)
    let currentAttempt = 0
    let heartbeatTimer = null

    // ▼ 初始化连接（自动携带Token）▼
    const connect = () => {
        const token = localStorage.getItem('token') || ''
        const protocols = ['Bearer', token] // 协议数组传递Token

        try {
            socket.value = new WebSocket(url, protocols)
            bindEvents()
        } catch (error) {
            handleError(error)
        }
    }

    // ▼ 事件绑定 ▼
    const bindEvents = () => {
        if (!socket.value) return

        socket.value.onopen = () => {
            isConnected.value = true
            currentAttempt = 0
            console.log('WebSocket 连接成功')
            startHeartbeat()
            flushMessageQueue() // 发送缓冲中的消息
        }

        socket.value.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data)
                messages.value.push(data)
                handleSystemMessage(data) // 处理系统级消息（如心跳响应）
            } catch (e) {
                console.error('消息解析失败:', e)
            }
        }

        socket.value.onerror = (error) => {
            handleError(error)
            scheduleReconnect()
        }

        socket.value.onclose = (event) => {
            isConnected.value = false
            if (!event.wasClean) {
                scheduleReconnect()
            }
        }
    }

    // ▼ 心跳检测（保持连接活跃）▼
    const startHeartbeat = () => {
        heartbeatTimer = setInterval(() => {
            if (isConnected.value) {
                send({ type: 'HEARTBEAT' })
            }
        }, 25000) // 25秒发送一次心跳
    }

    // ▼ 错误处理 ▼
    const handleError = (error) => {
        console.error('WebSocket错误:', error)
        ElNotification({
            title: '连接异常',
            message: '实时通知服务不可用，请检查网络',
            type: 'error'
        })
    }

    // ▼ 自动重连 ▼
    const scheduleReconnect = () => {
        if (currentAttempt < reconnectAttempts) {
            currentAttempt++
            setTimeout(() => {
                console.log(`尝试第 ${currentAttempt} 次重连...`)
                connect()
            }, reconnectInterval)
        }
    }

    // ▼ 发送消息（支持断线缓冲）▼
    const send = (data) => {
        if (isConnected.value) {
            socket.value.send(JSON.stringify(data))
        } else {
            messageQueue.value.push(data) // 网络中断时缓冲消息
        }
    }

    // ▼ 发送缓冲消息 ▼
    const flushMessageQueue = () => {
        while (messageQueue.value.length > 0) {
            const msg = messageQueue.value.shift()
            socket.value.send(JSON.stringify(msg))
        }
    }

    // ▼ 处理系统消息 ▼
    const handleSystemMessage = (data) => {
        switch (data.type) {
            case 'HEARTBEAT_ACK':
                console.log('心跳检测正常')
                break
            case 'AUTH_FAIL':
                ElNotification.error({ title: '认证失效', message: '请重新登录' })
                disconnect()
                window.location.reload()
                break
        }
    }

    // ▼ 安全断开连接 ▼
    const disconnect = () => {
        if (socket.value) {
            socket.value.close(1000, '用户主动断开')
            clearInterval(heartbeatTimer)
            isConnected.value = false
        }
    }

    // ▼ 组件卸载时自动清理 ▼
    onUnmounted(() => {
        disconnect()
    })

    return {
        socket,
        messages,
        isConnected,
        connect,
        disconnect,
        send
    }
}